﻿using System;
using System.Linq;
using DataFiller.DataStorage.Extension.Excel.Locaters;
using DataFiller.DataStorage.Holders;
using DataFiller.DataStorage.Regions;

namespace DataFiller.DataStorage.Extension.Regions
{
    public class ExcelRowRegion<T> : DataRegion<T>
    {
        /// <summary>
        /// max - min + 1
        /// </summary>
        public int RowCount
        {
            get
            {
                if (base._Records.Count == 0)
                    return 1;

                int mini = base._Records.Min
                (
                    p => (p.Locater as ExcelLocater).RowNumber
                );

                int max = base._Records.Max
                (
                    p => (p.Locater as ExcelLocater).RowNumber
                );

                return max - mini + 1;
            }
        }
        /// <summary>
        /// row number from excel template
        /// </summary>
        public int TemplateRowNumber { get; set; }
        /// <summary>
        /// row number that correctly fits the document had been filled
        /// </summary>
        public int StartRowNumber { get; set; }

        public override void AddHolder(IDataHolder holder)
        {
            ExcelLocater locater = holder.Locater as ExcelLocater;
            if (locater == null)
                throw new ArgumentException("given data holder is not contains a excel locater.");

            //calculate the holder's new row number
            if (locater.RowNumber >= this.TemplateRowNumber)
                locater.RowNumber = StartRowNumber + locater.RowNumber - TemplateRowNumber;
            else
                throw new ArgumentException("given holder is not contained in current region.");

            base.AddHolder(holder);
        }
    }
}
